package com.mall.service.authority.interceptor;


import com.mall.autoconfig.interceptor.BaseContext;
import com.mall.commons.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 *
 * @Date 2023-02-25 19:22
 * @Desc token拦截器
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {
    /**
     * Token鉴权
     *   成功：线程存入用户id以及Phone
     *   失败：抛出401异常
     *
     * @param request
     * @param response
     * @param handler
     * @return boolean
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取token
        String token = request.getHeader("Authorization");
        token = token.replace("Bearer ", "");
        //4. 合格，通过并将用户信息存入线程
            //4.1 从token中获取信息
        Claims claims = JwtUtils.getClaims(token);
        String userId = claims.get("id").toString();
            //4.2 存入User对象，并存入线程
        BaseContext.setCurrentId(userId);
        //5.0 放行
        return true;
    }

    /**
     * 清除线程中信息
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @return void
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContext.remove();
    }
}
